package com.byzk.p2p.admin.borrow.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.vo.PaymentRecordVo;
import com.byzk.p2p.admin.borrow.dao.BorrowDao;
import com.byzk.p2p.admin.borrow.dao.ChangeDao;
import com.byzk.p2p.admin.borrow.dao.TenderDao;
import com.byzk.p2p.admin.borrow.dao.TenderRankDao;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.Change;
import com.byzk.p2p.admin.borrow.dto.TenderRank;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.util.BorrowStatus;
import com.byzk.p2p.admin.borrow.vo.AllowChangeVo;
import com.byzk.p2p.admin.borrow.vo.BorrowTenderVo;
import com.byzk.p2p.admin.borrow.vo.ChangeAwaitVo;
import com.byzk.p2p.admin.borrow.vo.MyChangeVo;
import com.byzk.p2p.admin.borrow.vo.MySaleChangeVo;
import com.byzk.p2p.admin.borrow.vo.SalingChangeVo;
import com.byzk.p2p.admin.borrow.vo.TenderRankVo;
import com.byzk.p2p.admin.borrow.vo.UserTenderExportVo;
import com.byzk.p2p.admin.borrow.vo.UserTenderVo;
import com.byzk.p2p.admin.fuiou.service.PreAuthCancelService;
import com.byzk.p2p.admin.money.dao.BorrowPaymentDao;
import com.byzk.p2p.admin.money.dao.BorrowPaymentDetailDao;
import com.byzk.p2p.admin.money.dao.FundRecordDao;
import com.byzk.p2p.admin.money.dto.BorrowPayment;
import com.byzk.p2p.admin.money.dto.BorrowPaymentDetail;
import com.byzk.p2p.admin.money.dto.FundRecord;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.vo.FundDetailVo;
import com.byzk.p2p.admin.money.vo.FundRecordUserVo;
import com.byzk.p2p.admin.score.dao.ScoreRecordDao;
import com.byzk.p2p.admin.score.dto.ScoreRecord;
import com.byzk.p2p.admin.score.util.ScoreRuleUtil;
import com.byzk.p2p.admin.system.dao.MemberDao;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.system.vo.TenderChartVo;
import com.byzk.p2p.admin.user.dao.UserAccountDao;
import com.byzk.p2p.admin.user.dto.UserAccount;

@Service
public class TenderService {

	@Autowired
	private TenderDao tenderDao;
	@Autowired
	private UserAccountDao accountDao;
	@Autowired
	private FundRecordDao fundRecordDao;
	@Autowired
	private BorrowDao borrowDao;
	@Autowired
	private BorrowPaymentDao paymentDao;
	@Autowired
	private BorrowPaymentDetailDao detaiDao;
	@Autowired
	private FundRecordService fundRecordService;
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private UserAccountDao userAccountDao; 
	@Autowired
	private ScoreRecordDao scoreRecordDao;
	@Autowired
	private ChangeDao changeDao;
	@Autowired
	private TenderRankDao tenderRankDao;
	@Autowired
	private PreAuthCancelService preAuthCancelService ; 
	
	public PageInfo<UserTenderVo> listAll(UserTender vo){
		int count=tenderDao.count(vo);
		List<UserTenderVo> voList = tenderDao.select(vo);
		PageInfo<UserTenderVo> page = null ;
		if(count==0){
			page = new PageInfo<UserTenderVo>(count, vo.getIndex() , 1);
		}else{
			page = new PageInfo<UserTenderVo>(count, vo.getIndex() , count);
		}
		page.setPageList(voList);
		return page;
	}
	
	/**
	 * 我的投资	
	 * @param vo
	 * @return
	 * @author suker.zhou
	 */
	public PageInfo<UserTenderVo> myTender(UserTenderVo vo){
		int count=tenderDao.myTenderCount(vo);
		List<UserTenderVo> voList=tenderDao.myTender(vo);
		Double sumAmount = tenderDao.sumAmountByUserTenderVo(vo);
		for (UserTenderVo tenderVo : voList) {
			double percent=tenderVo.getPercent();
			
			double interest=BaseUtil.getInterestByType(tenderVo.getPaymentMode(), tenderVo.getAmount(), percent/100, tenderVo.getPeriod(),tenderVo.getDateUtil());
			if("borrow".equals(tenderVo.getStatus())){
				tenderVo.setAwaitInterest(interest);
			}
		}
		PageInfo<UserTenderVo> page=new PageInfo<UserTenderVo>(count, vo.getIndex() , vo.getLimit());
		page.setSum(sumAmount);
		page.setPageList(voList);
		return page;
	}
	
	/**
	 * 
	 * @param tender object对象 
	 * @param status new为新手标
	 * @return
	 */
	public Integer saveOrUpdateUserTender(UserTender tender){
		if(tender.getId()==null){
			/*新增用户投资记录*/
			tenderDao.insert(tender);
			Borrow borrow=borrowDao.getBorrowById(tender.getBorrowId());
			
			/*投标获取头衔开始*/
			List<UserTender> list = tenderDao.getByBorrowId(tender.getBorrowId());
			/* 投资金额等于标的未投金额，则满标，获取投标一锤定音头衔*/
			if(tender.getAmount().equals(borrow.getNotTenderMoney())){
				tenderRankDao.insert(new TenderRank(borrow.getId(), tender.getUserId(),tender.getId(), "一锤定音"));
				//第一个投标
				if(list.size() == 1){
					tenderRankDao.insert(new TenderRank(borrow.getId(), tender.getUserId(),tender.getId(), "快如闪电"));
					tenderRankDao.insert(new TenderRank(borrow.getId(), tender.getUserId(),tender.getId(), "任性土豪"));
				}else{
					/* 不是第一投标就判断其投标金额是否大于前一个人的投标金额。大于就获取任性土豪称号，否则什么也不做 */
					TenderRank rank = new TenderRank(borrow.getId(), "任性土豪");
					TenderRankVo rankVo = tenderRankDao.getByBorrowIdAndRank(rank);
					UserTender temp = tenderDao.getById(rankVo.getTenderId());
					if(tender.getAmount() > temp.getAmount()){
						rankVo.setTenderId(tender.getId());
						rankVo.setUserId(tender.getUserId());
						tenderRankDao.update(rankVo);
					}
				}
			}else{
				//第一个投标
				if(list.size() == 1){
					tenderRankDao.insert(new TenderRank(borrow.getId(), tender.getUserId(),tender.getId(), "快如闪电"));
					tenderRankDao.insert(new TenderRank(borrow.getId(), tender.getUserId(),tender.getId(), "任性土豪"));
				}else{
					/* 不是第一投标就判断其投标金额是否大于前一个人的投标金额。大于就获取任性土豪称号，否则什么也不做 */
					TenderRank rank = new TenderRank(borrow.getId(), "任性土豪");
					TenderRankVo rankVo = tenderRankDao.getByBorrowIdAndRank(rank);
					UserTender temp = tenderDao.getById(rankVo.getTenderId());
					if(tender.getAmount() > temp.getAmount()){
						rankVo.setTenderId(tender.getId());
						rankVo.setUserId(tender.getUserId());
						tenderRankDao.update(rankVo);
					}
				}
			}
			/*投标获取头衔结束*/
			
			/*修改用户账户金额*/
			UserAccount account=accountDao.getById(tender.getUserId());
			
			/*修改借款标的各项数据*/
			borrow.setTenderMoney(borrow.getTenderMoney()+tender.getAmount());
			borrow.setNotTenderMoney(borrow.getNotTenderMoney()-tender.getAmount());
			Double percent=borrow.getTenderMoney()/borrow.getAmount();
			if(percent==1){
				borrow.setStatus(BorrowStatus.CHECK);
			}
			int temp=(int)(percent*10000);
			percent = (double)temp/100;
			borrow.setSchedules(percent);
			borrowDao.updateBorrow(borrow);

			/*新增用户资金流水*/
			FundRecord record=new FundRecord();
			record.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
			record.setIncome(0.00);
			record.setExpend(0.00);
			record.setType(FundRecordType.Type.TENDER_FREEZEN.index);
			record.setUserId(tender.getUserId());
			record.setRemark("投资借款标");
			record.setTerminal("PC");
			record.setCreateTime(new Date());
			record.setBalance(account.getBalance()-tender.getAmount());
			record.setFreezen(tender.getAmount());
			record.setObjectId(tender.getId());
			fundRecordDao.insert(record);
			
			int type=1;
			if("DAY".equals(borrow.getDateUtil())){
				type=1;
			}
			if("MONTH".equals(borrow.getDateUtil())){
				type=2;
			}
			int tempScore=(int) (tender.getAmount()/100);

			MemberLevel level=getLevelByAmount(account.getScore()+tempScore);
			if(level!=null){
				account.setLevel(level.getId());
			}
			//增加积分
			ScoreRecord scoreRecord = new ScoreRecord();
			scoreRecord.setUserId(tender.getUserId());
			scoreRecord.setOptType("in");
			scoreRecord.setAmount(tempScore);
			scoreRecord.setWay("投资获得积分");
			scoreRecord.setTerminal("PC");
			scoreRecord.setCreateTime(new Date());
			scoreRecordDao.insert(scoreRecord);
			
			account.setScore(account.getScore()+tempScore);
			account.setTotalExpenses(account.getTotalExpenses()+tender.getAmount());
			account.setBalance(account.getBalance()-tender.getAmount());
			account.setFreezen(account.getFreezen()+tender.getAmount());
//			account.setNotUsedMoney(account.getNotUsedMoney()-tender.getAmount());
			accountDao.update(account);
//			//邀请奖励发放
//			List<UserTenderVo> tendVo = tenderDao.select(tender);
//			if(tendVo.size() == 1){
//				InviteRef inviteRef = inviteRefDao.getInviteRefByUserId(tender.getUserId());
//				UserAccount userAccount = accountDao.getByUserId(inviteRef.getInvitedUserId());
//				userAccount.setTotalAmount(userAccount.getTotalAmount()+2);
//				userAccount.setBalance(userAccount.getBalance()+2);
//				accountDao.update(userAccount);
//				
//				FundRecord recordVo=new FundRecord();
//				recordVo.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
//				recordVo.setIncome(2.00);
//				recordVo.setExpend(0.00);
//				recordVo.setType(FundRecordType.Type.INVITE.index);
//				recordVo.setUserId(tender.getUserId());
//				recordVo.setRemark("邀请奖励");
//				recordVo.setCreateTime(new Date());
//				recordVo.setBalance(userAccount.getBalance()+2);
//				recordVo.setFreezen(tender.getAmount());
//				fundRecordDao.insert(recordVo);
//			}
			return tender.getId();
		}else{
			tenderDao.update(tender);
			return tender.getId();
		}
	}
	
	
//	/**
//	 * 满标复审逻辑
//	 * @return
//	 * @throws Exception 
//	 */
//	public Integer compeleteBorrow(Borrow borrow) throws Exception{
//		/*
//		 * 1)更新用户投资记录各项数据
//		 */
//		System.out.println("---------满标开始------------"+borrow.getId());
//		List<UserTender> tenderList=tenderDao.getByBorrowId(borrow.getId());
//		List<UserAccount> accountList=new ArrayList<UserAccount>();
//		Double repayTotal=0.0,repayFund=0.0,repayInterset=0.0;
//		
//		for (UserTender tender : tenderList) {
//			//投资总利息计算
//			Double interset=BaseUtil.getInterestByType(borrow.getPaymentMode(), tender.getAmount(), (borrow.getPercent())/100, borrow.getDeadline(),borrow.getDateUtil());
//			tender.setRecoverInterest(interset);
//			tender.setRecoverFund(tender.getAmount());
//			tender.setRecoverAll(tender.getAmount()+interset);
//			tender.setRecovedMoney(0.0);
//			tender.setRecovedInterest(0.0);
//			tender.setRecovedFund(0.0);
//			tender.setAwaitFund(tender.getAmount());
//			tender.setAwaitInterest(interset);
//			tender.setAwaitTotal(tender.getAmount()+interset);
//			tender.setPeriodTotal(borrow.getPeriod());
//			tender.setRecovedPeriod(0);
//			tender.setRecovedAdvanceFee(0.0);
//			tender.setRecovedOverdueFee(0.0);
//			repayInterset+=interset;
//			System.out.println("--------利息--------"+repayInterset);
//			
//			repayFund+=tender.getAmount();
//			
//			UserAccount account1 = accountDao.getByUserId(tender.getUserId());
//			account1.setTotalAmount(account1.getTotalAmount()+interset);
//			account1.setFreezen(account1.getFreezen()-tender.getAmount());
//			accountDao.update(account1);
//			
//		}
//		
//		repayTotal=repayFund+repayInterset;
//		
//		BorrowApply borrowApply=borrowDao.getBorrowApplyById(borrow.getBorrowApplyId()); 
//		//借款用户
//		UserAccount userAccount=accountDao.getByUserId(borrowApply.getUserId());
//		userAccount.setBalance(userAccount.getBalance()+borrow.getAmount());
//		userAccount.setTotalAmount(userAccount.getTotalAmount()+borrow.getAmount());
//		userAccount.setRepay(userAccount.getRepay()+repayTotal);
//		userAccount.setTotalIncome(userAccount.getTotalIncome()+borrow.getAmount());
//		//userAccount.setNotUsedMoney(userAccount.getNotUsedMoney()+borrow.getAmount()-borrow.getAmount());
//		accountList.add(userAccount);
//		
//		accountDao.update(userAccount);
//		tenderDao.batchUpdate(tenderList);
//		
//		/*
//		 * 2)新增还款数据
//		 */
//		List<PaymentRecordVo> recordVoList=BaseUtil.generatePaymentRecord(borrow.getPaymentMode(), borrow.getAmount(), (borrow.getPercent())/100, borrow.getDeadline(), borrow.getCreateTime(),borrow.getDateUtil());
//		for (PaymentRecordVo detailVo : recordVoList) {
//			BorrowPayment pay=detailVo.convertItem(detailVo);
//			BorrowApply apply=borrowDao.getBorrowApplyById(borrow.getBorrowApplyId());
//			pay.setUserId(apply.getUserId());
//			pay.setBorrowId(borrow.getId());
//			pay.setStatus("N");
//			pay.setPaymentFund(0.0);
//			pay.setPaymentInterest(0.0);
//			pay.setPaymentTotal(0.0);
//			pay.setNotPaymentFund(detailVo.getFund());
//			pay.setNotPaymentInterest(detailVo.getInterest());
//			pay.setNotPaymentTotal(detailVo.getTotal());
//			pay.setCreateTime(new Date());
//			pay.setActualDate(null);
//			pay.setOverdueDay(0);
//			pay.setOverdueInterest(0.0);
//			pay.setOverdueFee(0.0);
//			//pay.setOrdId(SignUtils.autoOrdId());
//			paymentDao.insert(pay);
//			
//			/*
//			 * 3)新增还款明细数据
//			 */
//			Double tempInterset=0.0;
//			Double tempFund=0.0;
//			Double tempTotal=0.0;
//			List<BorrowPaymentDetail> detailList=new ArrayList<BorrowPaymentDetail>();
//			for (UserTender tender : tenderList) {
//				PaymentRecordVo record=BaseUtil.getInterestByTypeAndIndex(borrow.getPaymentMode(), tender.getAmount(), (borrow.getPercent())/100, borrow.getDeadline(),borrow.getDateUtil(),detailVo.getId());
//				BorrowPaymentDetail detail=record.convertDetail(record);
//				/**
//				 * 根据利息管理费
//				 */
//				UserAccount account=accountDao.getByUserId(tender.getUserId());
//				MemberLevel level=memberDao.getById(account.getLevel());
//				double discount=0.0;
//				if(level==null){
//					discount=0.1;
//				}else{
//					discount=level.getFeePercent();			
//				}
//				detail.setFee(BaseUtil.StringToDoubletoFixed2(detail.getNotPaymentInterest()*discount));
//				
//				detail.setUserId(tender.getUserId());
//				detail.setPaymentId(pay.getId());
//				detail.setBorrowId(borrow.getId());
//				detail.setTenderId(tender.getId());
//				detail.setStatus("N");
//				detail.setIsChange("N");
//				detail.setExpectDate(detailVo.getPaymentDate());
//				detail.setOverdueDay(0);
//				detail.setOverdueInterest(0.0);
//				detail.setOverdueFee(0.0);
//				detail.setActualDate(null);
//				detail.setCreateTime(new Date());
//				detailList.add(detail);
//				
//				tempInterset=tempInterset+detail.getNotPaymentInterest();
//				tempFund = tempFund + detail.getNotPaymentFund();
//				tempTotal  = tempTotal + detail.getNotPaymentTotal();
//			}
//			pay.setNotPaymentFund(tempFund);
//			pay.setNotPaymentInterest(tempInterset);
//			pay.setNotPaymentTotal(tempTotal);
//			paymentDao.update(pay);
//			
//			detaiDao.batchinsert(detailList);
//		}
//		
//		/*
//		 * 4)更改投资标状态
//		 */
//		borrow.setStatus(BorrowStatus.PAY);
//		borrow.setCheckTime(new Date());
//		borrow.setNotPaymentFund(borrow.getAmount());
//		borrow.setNotPaymentInterest(repayInterset);
//		borrow.setNotPaymentTotal(repayInterset+borrow.getAmount());
//		borrowDao.updateBorrow(borrow);
//		
//		addFundRecord(borrowApply.getUserId(), borrow.getAmount(), 0.0, "PC", "放款", FundRecordType.Type.GET.index,0.0);
//		return 1;
//	}
	
	/**
	 * 满标复审逻辑
	 * @return
	 * @throws Exception 
	 */
	public Integer compeleteBorrow(Borrow borrow) throws Exception{
		/*
		 * 1)更新用户投资记录各项数据，分3步：
		 * 1.更新投资用户user_tender表,2.更新投资用户账户user_Account表,3.更新借款用户账户user_Account表
		 */
		Integer borrowId = borrow.getId();//借款标id
		System.out.println("---------满标开始------------"+borrowId);
		//存储该标的投资者账户
		List<UserAccount> accountList=new ArrayList<UserAccount>();
		Double repayTotal=0.0,repayFund=0.0,repayInterset=0.0;
		
		//查询该标的投资者,user_tender表
		List<UserTender> tenderList=tenderDao.getByBorrowId(borrowId);
		for (UserTender tender : tenderList) {
			//投资者的投资金额
			double tenderAmount = tender.getAmount();
			//投资总利息计算
			Double interset=BaseUtil.getInterestByType(borrow.getPaymentMode(), tenderAmount, (borrow.getPercent())/100, borrow.getDeadline(),borrow.getDateUtil());
			tender.setRecoverInterest(interset);
			tender.setRecoverFund(tenderAmount);
			tender.setRecoverAll(tenderAmount+interset);
			tender.setRecovedMoney(0.0);
			tender.setRecovedInterest(0.0);
			tender.setRecovedFund(0.0);
			tender.setAwaitFund(tenderAmount);
			tender.setAwaitInterest(interset);
			tender.setAwaitTotal(tenderAmount+interset);
			tender.setPeriodTotal(borrow.getPeriod());
			tender.setRecovedPeriod(0);
			tender.setRecovedAdvanceFee(0.0);
			tender.setRecovedOverdueFee(0.0);
			//投资用户
			UserAccount userAccountTender = accountDao.getByUserId(tender.getUserId());
			userAccountTender.setTotalAmount(userAccountTender.getTotalAmount()+interset);
			userAccountTender.setFreezen(userAccountTender.getFreezen()-tenderAmount);
			accountList.add(userAccountTender);

			repayInterset+=interset;
			repayFund+=tenderAmount;//总本金
			System.out.println("--------利息--------"+repayInterset);
		}
		//总本息=总本金+总利息
		repayTotal=repayFund+repayInterset;
		//1,批量更新投资用户user_tender表
		tenderDao.batchUpdate(tenderList);
		//2,批量更新投资用户账户user_Account表
		accountDao.batchUpdate(accountList);
		//3,更新借款用户账户user_Account表
		//查询借款用户账户信息
		UserAccount userAccountApply=accountDao.getBorrowApplyAccount(borrow.getBorrowApplyId());
		userAccountApply.setBalance(userAccountApply.getBalance()+borrow.getAmount());
		userAccountApply.setTotalAmount(userAccountApply.getTotalAmount()+borrow.getAmount());
		userAccountApply.setRepay(userAccountApply.getRepay()+repayTotal);//待还金额
		userAccountApply.setTotalIncome(userAccountApply.getTotalIncome()+borrow.getAmount());
		accountDao.update(userAccountApply);
		
		/*
		 * 2)新增还款数据borrow_payment
		 */
		//还款明细列表
		List<BorrowPaymentDetail> paymentDetailList=new ArrayList<BorrowPaymentDetail>();
		List<PaymentRecordVo> recordVoList=BaseUtil.generatePaymentRecord(borrow.getPaymentMode(), borrow.getAmount(), (borrow.getPercent())/100, borrow.getDeadline(), borrow.getCreateTime(),borrow.getDateUtil());
		for (PaymentRecordVo paymentRecordVo : recordVoList) {
			BorrowPayment pay=paymentRecordVo.convertItem(paymentRecordVo);
			pay.setUserId(userAccountApply.getUserId());//借款者id
			pay.setBorrowId(borrowId);
			pay.setStatus("N");
			pay.setPaymentFund(0.0);
			pay.setPaymentInterest(0.0);
			pay.setPaymentTotal(0.0);
			pay.setNotPaymentFund(paymentRecordVo.getFund());
			pay.setNotPaymentInterest(paymentRecordVo.getInterest());
			pay.setNotPaymentTotal(paymentRecordVo.getTotal());
			pay.setCreateTime(new Date());
			pay.setActualDate(null);
			pay.setOverdueDay(0);
			pay.setOverdueInterest(0.0);
			pay.setOverdueFee(0.0);
			//pay.setOrdId(SignUtils.autoOrdId());
			paymentDao.insert(pay);
			
			/*
			 * 3)新增还款明细数据borrow_payment_detail
			 */
			Double tempInterset=0.0;
			Double tempFund=0.0;
			Double tempTotal=0.0;
			for (UserTender tender : tenderList) {
				PaymentRecordVo record=BaseUtil.getInterestByTypeAndIndex(borrow.getPaymentMode(), tender.getAmount(), (borrow.getPercent())/100, borrow.getDeadline(),borrow.getDateUtil(),paymentRecordVo.getId());
				BorrowPaymentDetail detail=record.convertDetail(record);
				//计算利息管理费
				double feePercent =accountDao.getFeePercentByUserId(tender.getUserId());
				detail.setFee(BaseUtil.StringToDoubletoFixed2(detail.getNotPaymentInterest()*feePercent));
				detail.setUserId(tender.getUserId());
				detail.setPaymentId(pay.getId());
				detail.setBorrowId(borrowId);
				detail.setTenderId(tender.getId());
				detail.setStatus("N");
				detail.setIsChange("N");
				detail.setExpectDate(paymentRecordVo.getPaymentDate());
				detail.setOverdueDay(0);
				detail.setOverdueInterest(0.0);
				detail.setOverdueFee(0.0);
				detail.setActualDate(null);
				detail.setCreateTime(new Date());
				paymentDetailList.add(detail);
				
				tempInterset=tempInterset+detail.getNotPaymentInterest();
				tempFund = tempFund + detail.getNotPaymentFund();
				tempTotal  = tempTotal + detail.getNotPaymentTotal();
			}
			pay.setNotPaymentFund(tempFund);
			pay.setNotPaymentInterest(tempInterset);
			pay.setNotPaymentTotal(tempTotal);
			paymentDao.update(pay);
			
		}
		detaiDao.batchinsert(paymentDetailList);
		
		/*
		 * 4)更改投资标状态
		 */
		borrow.setStatus(BorrowStatus.PAY);
		borrow.setCheckTime(new Date());
		borrow.setNotPaymentFund(borrow.getAmount());
		borrow.setNotPaymentInterest(repayInterset);
		borrow.setNotPaymentTotal(repayInterset+borrow.getAmount());
		borrowDao.updateBorrow(borrow);
		
		/*
		 * 5)新增资金明细
		 */
		addFundRecord(userAccountApply.getUserId(), borrow.getAmount(), 0.0, "PC", "放款", FundRecordType.Type.GET.index,0.0);
		return 1;
	}

	/**
	 * 新手标满标复审逻辑
	 * @return
	 */
	public Integer compeleteNewBorrow(Borrow borrow){
		/*
		 * 1)更新用户投资记录各项数据
		 */
		List<UserTender> tenderList=tenderDao.getByBorrowId(borrow.getId());
		Double repayInterset=0.0;
		for (UserTender tender : tenderList) {
			Double interset=BaseUtil.getNewBorrowInterest(tender.getAmount(), (borrow.getPercent())/100, borrow.getDeadline());
			repayInterset=repayInterset+interset;
		}
		
		Double repayTotal=0.0,repayFund=0.0;
		System.out.println("---------borrowId："+borrow.getId());
		System.out.println("---------本金："+borrow.getAmount()+"，利息："+borrow.getPercent()+"，期限："+borrow.getDeadline()+"-------");
		PaymentRecordVo detailVo=BaseUtil.generateNewsPaymentRecord(borrow.getAmount(), (borrow.getPercent())/100, borrow.getDeadline(), new Date());
		
		BorrowApply apply=borrowDao.getBorrowApplyById(borrow.getBorrowApplyId());
		/*
		 * 2)新增还款数据
		 */
		BorrowPayment pay=detailVo.convertItem(detailVo);
		pay.setUserId(apply.getUserId());
		pay.setBorrowId(borrow.getId());
		pay.setStatus("N");
		pay.setPaymentFund(0.0);
		pay.setPaymentInterest(0.0);
		pay.setPaymentTotal(0.0);
		pay.setNotPaymentFund(detailVo.getFund());
		pay.setNotPaymentInterest(repayInterset);
		pay.setNotPaymentTotal(repayInterset+detailVo.getFund());
		pay.setCreateTime(new Date());
		pay.setActualDate(null);
		pay.setOverdueDay(0);
		pay.setOverdueInterest(0.0);
		pay.setOverdueFee(0.0);
		paymentDao.insert(pay);
		System.out.println("---------总利息："+detailVo.getInterest()+"-------");
		for (UserTender tender : tenderList) {
			Double interset=BaseUtil.getNewBorrowInterest(tender.getAmount(), (borrow.getPercent())/100, borrow.getDeadline());
			System.out.println("---------分利息："+interset+"-------");
			tender.setRecoverInterest(interset);
			tender.setRecoverFund(tender.getAmount());
			tender.setRecoverAll(tender.getAmount()+interset);
			tender.setRecovedMoney(0.0);
			tender.setRecovedInterest(0.0);
			tender.setRecovedFund(0.0);
			tender.setAwaitFund(tender.getAmount());
			tender.setAwaitInterest(interset);
			tender.setAwaitTotal(tender.getAmount()+interset);
			tender.setPeriodTotal(1); //此处由borrow.getPeriod()改为1期，因为新手标是一次性还款只有1期
			tender.setRecovedPeriod(0);
			tender.setRecovedAdvanceFee(0.0);
			tender.setRecovedOverdueFee(0.0);
			
			repayTotal=repayTotal+tender.getRecoverAll();
			repayFund+=tender.getAmount();
			
			/*
			 * 3)新增还款明细数据
			 */
			List<BorrowPaymentDetail> detailList=new ArrayList<BorrowPaymentDetail>();
			PaymentRecordVo record=BaseUtil.getInterest(tender.getAmount(), (borrow.getPercent())/100, borrow.getDeadline());
			BorrowPaymentDetail detail=record.convertDetail(record);
			System.out.println("---------分利息2："+detail.getPaymentInterest()+"-------");
			/**
			 * 根据利息管理费
			 */
			UserAccount userAccount=accountDao.getByUserId(tender.getUserId());
			MemberLevel level=memberDao.getById(userAccount.getLevel());
			double discount=0.0;
			if(level==null){
				discount=0.1;
			}else{
				discount=level.getDiscount()/100;
			}
					
			detail.setFee(BaseUtil.StringToDoubletoFixed2(detail.getPaymentInterest()*discount));
			detail.setUserId(tender.getUserId());
			detail.setPaymentId(pay.getId());
			detail.setBorrowId(borrow.getId());
			detail.setTenderId(tender.getId());
			detail.setStatus("N");
			detail.setIsChange("N");
			detail.setExpectDate(detailVo.getPaymentDate());
			detail.setOverdueDay(0);
			detail.setOverdueInterest(0.0);
			detail.setOverdueFee(0.0);
			detail.setActualDate(null);
			detail.setCreateTime(new Date());
			detailList.add(detail);
			detaiDao.batchinsert(detailList);
			
			UserAccount userAccount2 = accountDao.getByUserId(tender.getUserId());
			userAccount2.setTotalAmount(userAccount2.getTotalAmount()+interset);
			userAccount2.setFreezen(userAccount2.getFreezen()-tender.getAmount());
			accountDao.update(userAccount2);
		}
		
		tenderDao.batchUpdate(tenderList);
		
		/*
		 * 4)更改投资标状态
		 */
		borrow.setStatus(BorrowStatus.PAY);
		borrow.setNotPaymentFund(repayFund);
		borrow.setNotPaymentInterest(detailVo.getInterest());
		borrow.setNotPaymentTotal(repayTotal);
		borrow.setCheckTime(new Date());
		borrow.setAssuranceMoney(borrow.getAmount()*0.03);
		borrowDao.updateBorrow(borrow);
		
		UserAccount borrowAccount=accountDao.getByUserId(apply.getUserId());
		borrowAccount.setBalance(borrowAccount.getBalance()+repayFund-borrow.getAmount()*0.10);
		borrowAccount.setTotalAmount(borrowAccount.getTotalAmount()+repayFund-borrow.getAmount()*0.10);
		borrowAccount.setRepay(borrowAccount.getRepay()+repayTotal);
		borrowAccount.setTotalIncome(borrowAccount.getTotalIncome()+repayFund-borrow.getAmount()*0.10);
//		borrowAccount.setNotUsedMoney(borrowAccount.getNotUsedMoney()+borrow.getAmount()-borrow.getAmount()*0.10);
		accountDao.update(borrowAccount);
		
		addFundRecord(apply.getUserId(), borrow.getAmount(), 0.0, "PC", "借款成功", FundRecordType.Type.GET.index,borrowAccount.getFreezen());
		return 1;
	}
	

	
	public List<BorrowTenderVo> getTenderByVo(UserTenderVo userTender){
		return tenderDao.getUserTenderList(userTender);
	}
	
	
	public PageInfo<BorrowTenderVo> getUserTender(UserTenderVo userTender){
		int count=tenderDao.getUserTenderCount(userTender);
		List<BorrowTenderVo> voList=tenderDao.getUserTender(userTender);
		PageInfo<BorrowTenderVo> page=new PageInfo<BorrowTenderVo>(count,userTender.getIndex(),userTender.getLimit());
		page.setPageList(voList);
		return page;
	}
	
	/**
	 * 获取投资用户投的某一个标的信息
	 * @param userId
	 * @param borrowId
	 * @return
	 */
	public BorrowTenderVo getUserTenderInfo(Integer userId, Integer borrowId){
		UserTenderVo userTender = new UserTenderVo();
		userTender.setUserId(userId);
		userTender.setBorrowId(borrowId);
		userTender.setStart(0);
		userTender.setLimit(1);
		List<BorrowTenderVo> list = tenderDao.getUserTender(userTender);
		BorrowTenderVo borrowTender = null;
		if(list != null && list.size()>0) {
			borrowTender = list.get(0);
		}
		return borrowTender;
	}
	
	/**
	 * 账户中心-资金明细
	 * @param userId
	 * @return
	 */
	public FundDetailVo getFundDetailVo(Integer userId){
		FundDetailVo detail=new FundDetailVo();
		detail.setAwaitCount(tenderDao.awaitCount(userId));
		ChangeAwaitVo await=tenderDao.sumChangeAwait(userId,null);
		//待收本金
		detail.setAwaitFund(tenderDao.sumAwaitFund(userId)+await.getPaymentFund());
		//待收利息
		detail.setAwaitInterest(tenderDao.sumAwaitInterest(userId)+await.getPaymentInterest());
		//待收总额
		UserAccount account=accountDao.getByUserId(userId);
		detail.setAwaitTotal(tenderDao.sumAwaitTotal(userId)+await.getPaymentTotal()+account.getAwait());
		
		detail.setCount(tenderDao.recovedCount(userId));
		//已收本金
		detail.setFund(tenderDao.sumRecovedFund(userId));
		//已收利息
		detail.setInterest(tenderDao.sumRecoverInterest(userId));
		detail.setTotal(detail.getFund()+detail.getInterest());
		detail.setTotalCount(tenderDao.totalCount(userId));
		detail.setTotalTenderMoney(tenderDao.sumTenderMoney(userId));
		detail.setPayCount(tenderDao.sumPayTotal(userId));
		detail.setPayFund(tenderDao.sumPayFund(userId));
		detail.setPayInterest(tenderDao.sumPayInterest(userId));
		return detail;
	}
	
	/**
	 * 可以债权转让的借款
	 * @param userId
	 * @return
	 */
	public PageInfo<AllowChangeVo> listAllowChange(UserTender tender){
		int count = tenderDao.changeCount(tender);
		//第一次进行债权转让的债权
		List<AllowChangeVo> voList= tenderDao.listAllowChange(tender);
//		//可进行第二次债权转让的债券，通过用户id获取该用户承接15天以上，并且只出让过一次的债权
//		List<AllowChangeVo> list = changeDao.changeListByChangeUserId(tender.getUserId());
//		for(AllowChangeVo vo : list){
//			List<Change> changeList = changeDao.getChangeByTenderIdAndBorrowId(vo.getBorrowId(), vo.getTenderId());
//			if(changeList.size()<2){
//				voList.add(vo);
//			}
//		}
		PageInfo<AllowChangeVo> page= new PageInfo<AllowChangeVo>(count,tender.getIndex(),tender.getLimit());
		page.setPageList(voList);
		return page;
	}
	
	public UserTender getById(Integer id){
		return tenderDao.getById(id);
	}
	
	public List<MySaleChangeVo> listMySaleChange(Integer userId){
		return tenderDao.listMySaleChange(userId);
	}
	
	public PageInfo<SalingChangeVo> listSalingChange(UserTender tender){
		int count = tenderDao.salingChangeCount(tender);
		List<SalingChangeVo> voList= tenderDao.listSalingChange(tender);
		PageInfo<SalingChangeVo> page= new PageInfo<SalingChangeVo>(count,tender.getIndex(),tender.getLimit());
		page.setPageList(voList);
		return page;
	}
	
	/**
	 * 帮投资人获取的收益
	 * @return
	 */
	public Double getAllRecovedInterest(){
		return tenderDao.getAllRecovedInterest();
	}
	
	/**
	 * 平台总投资金额
	 * @return
	 */
	public Double getAllTenderAmount(Date start,Date end){
		return tenderDao.getAllTenderAmount(start,end);
	}
	
	/**
	 * 平台当年每月的投资额
	 * @return
	 */
	public List<UserTender> getMonthTender(Integer year){
		return tenderDao.getUserTenderGroupMonth(year);
	}
	
	public List<UserTenderVo> top5TenderUser(){
		return tenderDao.top5TenderUser();
	}
	
	public Integer saveOrUpdate(UserTender tender){
		if(tender.getId()==null){
			return tenderDao.insert(tender);
		}else{
			return tenderDao.update(tender);
		}
	}
	/**
	 * 根据borrowId查询所有借款人信息
	 * @param borrowId
	 * @return
	 */
	public List<UserTenderVo> myBorrowTender(Integer borrowId){
		return tenderDao.myBorrowTender(borrowId);
	}	
	
	public Integer addFundRecord(Integer uid,Double income,Double expend,String terminal,String remark,Integer type,Double freezen){
		FundRecord record=new FundRecord();
		record.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
		record.setCreateTime(new Date());
		record.setRemark(remark);
		record.setType(type);
		record.setUserId(uid);
		record.setIncome(income);
		record.setExpend(expend);
		record.setTerminal(terminal);		
		UserAccount account=userAccountDao.getById(uid);
		Double balance=account.getBalance();
		record.setFreezen(account.getFreezen());
		record.setBalance(balance);
		return fundRecordDao.insert(record);
	}
	
	public Double sumAwaitByNotChange(Integer tenderId){
		return tenderDao.sumAwaitByNotChange(tenderId);
	}
	
//	/**
//	 * 是否赠送注册奖励
//	 * 1.新用户注册
//	 * 2.注册奖励和邀请奖励仅限rewardNumber人
//	 * 注意：用户注册 注册奖励会有冻结金额
//	 * @param userId 用户id
//	 * @param terminal 投资终端
//	 * @param rewardNumber 奖励的人数
//	 * @return
//	 */
//	private boolean isGiveAmount(Integer userId,String terminal,Integer rewardNumber){
//		if (rewardNumber == null) {
//			return false;
//		}
//		FundRecordUserVo fundRecordUserVo = new FundRecordUserVo();
//		fundRecordUserVo.setType(FundRecordType.Type.REGISTER.index);
//		fundRecordUserVo.setRemark("注册奖励（冻结金额）");
//		fundRecordUserVo.setTerminal(terminal);
//		fundRecordUserVo.setUserId(userId);
//		int count = fundRecordService.getFundRecordCount(fundRecordUserVo);
//		return (count>0 && getSumFundRecord(terminal)<=rewardNumber)?true:false;
//	}
	
	/**
	 * 获取注册奖励+邀请奖励所有已赠送的资金记录
	 * @param terminal 投资终端
	 * @return
	 */
	public int getSumFundRecord(String terminal){
		FundRecordUserVo inviteUserVo = new FundRecordUserVo();
		inviteUserVo.setRemark("邀请奖励");
		inviteUserVo.setTerminal(terminal);
		int inviteCount = fundRecordService.getFundRecordCount(inviteUserVo);
		
		FundRecordUserVo registerUserVo = new FundRecordUserVo();
		registerUserVo.setType(FundRecordType.Type.REGISTER.index);
		registerUserVo.setRemark("注册奖励（资金解冻）");
		registerUserVo.setTerminal(terminal);
		int registerCount = fundRecordService.getFundRecordCount(registerUserVo);
		return registerCount+inviteCount;//邀请奖励含邀请人和被邀请人
	}
	
//	//获取注册冻结资金流水
//	private FundRecordUserVo getFundRecordUserVo(Integer userId,String terminal){
//		FundRecordUserVo registerUserVo = new FundRecordUserVo();
//		registerUserVo.setType(FundRecordType.Type.REGISTER.index);
//		registerUserVo.setRemark("注册奖励（冻结金额）");
//		registerUserVo.setTerminal(terminal);
//		registerUserVo.setUserId(userId);
//		FundRecordUserVo fundRecordUserVo = fundRecordService.getFundRecord(registerUserVo);
//		return fundRecordUserVo;
//	}
	
	public List<TenderChartVo> groupByDate(Date date){
		return tenderDao.groupByDate(date);
	}
	
	public List<UserTenderVo> exportList(UserTenderExportVo vo){
		return tenderDao.listByExportVo(vo);
	}
	
	/**
	 * 投资总额
	 * @return
	 */
	public Double getAllInvestment(){
		return tenderDao.getAllInvestment();
	}
	/**
	 * 待收总额
	 * @return
	 */
	public Double getAllAwait(){
		return tenderDao.getAllAwait();
	}
	
	public UserTender selectByCode(String code){
		return tenderDao.getByCode(code);
	}
	
	public List<UserTender> listTender(Integer borrowId){
		return tenderDao.getByBorrowId(borrowId) ;
	}
	
	public Double sumMoney(Integer userId,Integer borrowId){
		return tenderDao.sumMoney(userId, borrowId);
	}
	
	public MemberLevel getLevelByAmount(Integer amount){
		
		List<MemberLevel> levelList=memberDao.listAll();
		for (int i = 0; i <levelList.size(); i++) {
			Double temp=levelList.get(i).getMax();
			if(amount>=temp){
				return levelList.get(i);
			}else{
				continue;
			}
		}
		return null;
	}
	
	public Integer stayStillCount(Integer id){
		return tenderDao.stayStillCount(id);
	}

	public Double sumTenderAmount(Integer userId) {
		return tenderDao.sumTenderAmount(userId);
	}
	
	public Double sumTenderInterest(Integer userId){
		return tenderDao.sumTenderInterest(userId);
	}

	public int addTender(int borrowId, int userId, double amount,String code,String contract_no) {
		

		Borrow borrow=borrowDao.getBorrowById(borrowId);
		if(borrow.getNotTenderMoney() < amount || borrow.getStatus().equals(BorrowStatus.CHECK)){
			//预授权撤销
//			preAuthCancelService.preAuthCancel(borrowId, userId, contract_no);
			return 0;
		}
		//更新借款标信息
		borrow.setTenderMoney(borrow.getTenderMoney()+amount);
		borrow.setNotTenderMoney(borrow.getNotTenderMoney()-amount);
		Double percent=borrow.getTenderMoney()/borrow.getAmount();
		if(percent==1){
			borrow.setStatus(BorrowStatus.CHECK);
		}
		int temp=(int)(percent*10000);
		percent = (double)temp/100;
		borrow.setSchedules(percent);
		borrowDao.updateBorrow(borrow);
		
		//增加投资记录
		UserTender userTender = new UserTender();
		userTender.setUserId(userId);
		userTender.setBorrowId(borrowId);
		userTender.setChanges("N");
		userTender.setRepayFinish("N");
		userTender.setAmount(amount);
		userTender.setCreateTime(new Date());
		userTender.setTerminal("PC");
		userTender.setIsAuto("N");
		userTender.setCode(code);
		userTender.setContractNo(contract_no);
		tenderDao.insert(userTender);
		
		
		/** 添加首投奖励 **/
		List<UserTenderVo> tenderList = listUserTenderByBorrowId(borrowId);
		UserAccount tenderAccount=accountDao.getByUserId(userId);
		if(tenderList != null && tenderList.size() == 1) {
			tenderAccount.setStayAmount(tenderAccount.getStayAmount()+20.0);
			//增加投资用户资金流水
			FundRecord record=new FundRecord();
			record.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
			record.setIncome(20.00);
			record.setExpend(0.00);
			record.setType(FundRecordType.Type.STAY_MONEY.index);
			record.setUserId(userId);
			record.setRemark("首投奖励");
			record.setTerminal("PC");
			record.setCreateTime(new Date());
			record.setBalance(tenderAccount.getBalance());
			record.setFreezen(0.00);
			record.setObjectId(userTender.getId());
			fundRecordDao.insert(record);
		}
		
		/** 累计投标超过10W奖励 **/
		Double sumTender = sumMoney(userId, borrowId);
		if(sumTender >= 100000.0) {
			tenderAccount.setStayAmount(tenderAccount.getStayAmount()+200.0);
			//增加投资用户资金流水
			FundRecord record=new FundRecord();
			record.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
			record.setIncome(200.00);
			record.setExpend(0.00);
			record.setType(FundRecordType.Type.STAY_MONEY.index);
			record.setUserId(userId);
			record.setRemark("投标奖励");
			record.setCreateTime(new Date());
			record.setBalance(tenderAccount.getBalance());
			record.setFreezen(0.00);
			record.setObjectId(userTender.getId());
			fundRecordDao.insert(record);
		}
		
		//增加投资用户资金流水
		FundRecord record=new FundRecord();
		record.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
		record.setIncome(0.00);
		record.setExpend(0.00);
		record.setType(FundRecordType.Type.TENDER_FREEZEN.index);
		record.setUserId(userId);
		record.setRemark("投资借款标");
		record.setTerminal("PC");
		record.setCreateTime(new Date());
		record.setBalance(tenderAccount.getBalance()-amount);
		record.setFreezen(amount);
		record.setObjectId(userTender.getId());
		fundRecordDao.insert(record);
		
		
		//更新积分信息
		int count=0;
		if("MONTH".equals(borrow.getDateUtil())){
			count=ScoreRuleUtil.calc(borrow.getDeadline(), amount);
		}else{
			if(borrow.getDeadline()>=30){
				int num=(int)borrow.getDeadline()/30;
				count=ScoreRuleUtil.calc(num, amount);
			}else{
				count=(int)amount/300;
			}
		}
		tenderAccount.setScore(tenderAccount.getScore()+count);
		
		if(count>0){
			ScoreRecord entity=new ScoreRecord();
			entity.setUserId(userId);
			entity.setOptType("in");
			entity.setAmount(count);
			entity.setWay("投标积分");
			entity.setCreateTime(new Date());
			entity.setTerminal("PC");
			scoreRecordDao.insert(entity);
		}
		//更新投资人账户
		tenderAccount.setBalance(tenderAccount.getBalance()-amount);
		tenderAccount.setFreezen(tenderAccount.getFreezen()+amount);
//		tenderAccount.setNotUsedMoney((tenderAccount.getNotUsedMoney()-amount>0)?tenderAccount.getNotUsedMoney()-amount:0);
		accountDao.update(tenderAccount);
		return 1;
	}
	
	/**
	 * 获取投资人总数
	 * @return
	 */
	public int getTenderpeopleCount() {
		return tenderDao.getTenderpeopleCount();
	}
	
	/**
	 * 获取一个标的所有投资记录
	 * @param params
	 * @param index
	 * @param limit
	 * @return
	 */
	public List<UserTenderVo> listUserTenderByBorrowId(Integer borrowId){
		return tenderDao.listUserTenderByBorrowId(borrowId);
	}
	
	/**
	 * 
	* <p>Description:承接标赚取的收益 </p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年11月8日下午4:30:57
	 */
	public Double sumChangeTenderInterest(Integer userId) {
		Double recoverAmount = 0.00;
		List<String> userList = new ArrayList<String>();
		Change change = new Change();
		change.setChangeUserId(userId);
		List<MyChangeVo> voList = changeDao.listByChangeUserId(change);
		if (voList != null && voList.size() > 0) {
			for (MyChangeVo item : voList) {
				if (item.getUserId() != null) {
					if (userList.contains(item.getUserId())) {
						continue;
					}
					recoverAmount += tenderDao.sumChangeTenderInterest(Integer.parseInt(item.getUserId()));
					userList.add(item.getUserId());
				}
			}
		}
		return recoverAmount;
	}

}



